'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: 8_study_unsupport_function_model.py
* @Time: 2025/11/3
* @All Rights Reserve By Brtc
'''
import json
import os
from typing import Type, Any, TypedDict, Dict, Optional

import dotenv
import requests
from langchain_community.tools import GoogleSerperRun
from langchain_community.utilities import GoogleSerperAPIWrapper
from langchain_core.messages import ToolMessage
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough, RunnableConfig
from langchain_core.tools import BaseTool, render_text_description_and_args
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
dotenv.load_dotenv()

class GaodeWeatherShema(BaseModel):
    city:str = Field(description="需要查询天气的城市,例如:武汉")

class GaodeWeatherTool(BaseTool):
    """根据传入的城市名称运行调用api 获取城市的天气预报信息"""
    name:str = "llmops_gaode_weather_tool"
    description:str = "当你查询天气的时候可以调用这个工具"
    args_schema:Type[BaseModel] = GaodeWeatherShema

    def _run(self, *args:Any, **kwargs:Any) -> Any:
        try:
            gaode_api_key = os.getenv("GAODE_API_KEY")
            gaode_api_url = os.getenv("GAODE_API_URL")
            if not gaode_api_key or not gaode_api_url:
                return f"请配置高德开放API_KEY 和 URL"
            else:
                #1、从参数中获取城市
                city = kwargs.get("city")
                #2、开始请求 高德服务获取 adcode
                session = requests.session()
                #3、行政code 请求
                city_response = session.request(
                    method="GET",
                    url = f"{gaode_api_url}/config/district?key={gaode_api_key}&keywords={city}&subdistrict=0",
                    headers={"Content-Type": "application/json; charset=utf-8"},
                )
                city_response.raise_for_status()
                city_data = city_response.json()
                if city_data.get("info") == "OK":
                    ad_code = city_data["districts"][0]["adcode"]
                    weather_info = session.request(
                        method="GET",
                        url=f"{gaode_api_url}/weather/weatherInfo?key={gaode_api_key}&city={ad_code}&extensions=all"
                    )
                    weather_info.raise_for_status()
                    weather_data = weather_info.json()
                    if weather_data.get("info") == "OK":
                        #返回天气的结果
                        return json.dumps(weather_data)
                    else:
                        return f"最后请求参数出错！！"
                else:
                    return f"请求城市编码出错！"
        except Exception as e:
            return f"开始获取天气的时候就出错了！{str(e)}"

class GoogleSerperSchema(BaseModel):
    query:str = Field(description="执行谷歌搜索的查询语句")


class ToolCallRequest(TypedDict):
    """工具调用字典"""
    name:str
    arguments: Dict[str, any]



gaode_weather = GaodeWeatherTool()
google_serper = GoogleSerperRun(
    name = "google_serper",
    description = "一个底层本的谷歌工具",
    args_schema= GoogleSerperSchema,
    api_wrapper=GoogleSerperAPIWrapper(),
)
tool_dict = {
    google_serper.name: google_serper,
    gaode_weather.name: gaode_weather,
}
tools = [tool for tool in tool_dict.values()]

"""
* @Author Leon-liao
* @Function:
* @Description //TODO 
* @Date :2025/11/3  20:06
* @Param:
"""
def invoke_tool(tool_call_request:ToolCallRequest, config:Optional[RunnableConfig]=None)->Any:
    """
    我们可使用的执行工具调用函数
    :param tool_call_request: 一个包含函数名和参数的字典, 名称必须与现有函数保持一致，参数是该函数的参数
    :param config:  Langchain使用的 回调参数配置信息
    :return: 返回工具调用信息
    """
    tool_name_to_tool = {tool.name:tool for tool in tools}
    name = tool_call_request["name"]
    requested_tool = tool_name_to_tool[name]
    print("工具调用:", name)
    print("调用参数:", tool_call_request["arguments"])
    return requested_tool.invoke(tool_call_request["arguments"], config= config)


system_prompt = """ 
您是一个由OpenAI开发的聊天机器人，可以访问以下一组工具。
以下是每个工具的名称和描述：
 
{rendered_tools}
 
根据用户输入，返回要使用的工具的名称和输入。
将您的响应作为具有`name`和`arguments`键的JSON块返回。
`arguments`应该是一个字典，其中键对应于参数名称，值对应与请求的值。
"""
prompt = ChatPromptTemplate.from_messages([
    ("system", system_prompt),
    ("human", "{query}")
]).partial(rendered_tools=render_text_description_and_args(tools))

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

chain = (
    {"query":RunnablePassthrough()}
    |prompt
    |llm
    |JsonOutputParser()
    |RunnablePassthrough.assign(output = invoke_tool)
)
print(chain.invoke("你好 请问今天的 纳斯达克指数"))






